package com.example.customcow;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import org.apache.http.NameValuePair;
import org.apache.http.message.BasicNameValuePair;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import android.view.View.OnClickListener;

import android.app.ProgressDialog;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.v4.app.DialogFragment;
import android.support.v4.app.Fragment;
import android.support.v4.app.ListFragment;
import android.text.Editable;
import android.util.Log;
import android.view.ContextMenu;
import android.view.ContextMenu.ContextMenuInfo;
import android.view.LayoutInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.AutoCompleteTextView;
import android.widget.EditText;
import android.widget.ListAdapter;
import android.widget.ListView;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.SimpleAdapter;
import android.widget.Spinner;
import android.widget.Toast;

public class FragmentTab1 extends  Fragment    {
	JSONArray Item = null;
	private ProgressDialog pDialog;
	JSONParser jParser = new JSONParser();
	ArrayList sa;
	ArrayList<HashMap<String, String>> ListItem;
	ArrayList<HashMap<String,String>>Ganados;
	ListAdapter mAdapter = null;
	Spinner DesplegadoTipo;
	ListView mListView = null;
	RadioButton RadioRaza=null;
	RadioButton RadioTipoGanado=null;
	RadioGroup RadioGrupo=null;
	AutoCompleteTextView NombreCliente=null;
	int success=0;

	Sistema_Ganadero objetoDetalle = new Sistema_Ganadero();
	private static final String TAG_SUCCESS = "success";
	private static final String TAG_TIPOGANADO = "tipoganado";
	private static String TAG_IDTIPO="";
	private static String TAG_NOMBREGANADO="";

	public static int  prueba=0;
	
	public static String url_all_Sucursales = "http://10.0.0.2/android_connectmio/php_recuperaTipoGanado.php";
	private static final String TAG_PRODUCTOS = "productos";
	private static final String TAG_PID = "elid";
	private static final String TAG_NAME = "nombre";
  private static final String TAG_PRECIO="precio";
  private static final String TAG_CANTIDAD="value";
  private static String TAG_CODBARRA="codbarra";
	
	public View onCreateView(LayoutInflater inflater, ViewGroup container,
			Bundle savedInstanceState) {

		// Get the view from fragmenttab1.xml
		View view = inflater.inflate(R.layout.fragmenttab1, container, false);
	
		mListView = (ListView) view.findViewById(R.id.lv_items);
		DesplegadoTipo= (Spinner) view.findViewById(R.id.tipoGanado);
		ListItem=  new ArrayList<HashMap<String, String>>();
		Ganados=new ArrayList<HashMap<String,String>>();
		RadioRaza=(RadioButton) view.findViewById(R.id.radioraza);
		RadioTipoGanado=(RadioButton)view.findViewById(R.id.radiotipoganado);
		RadioGrupo=(RadioGroup)view.findViewById(R.id.radioGroup1);
		RefreshList();
		NombreCliente=(AutoCompleteTextView) view.findViewById(R.id.NombreCliente);
				//new	LoadAllProducts().execute();
		
		 registerForContextMenu(mListView);
		
		
		
		
		mListView.setOnItemLongClickListener(new AdapterView.OnItemLongClickListener() {
          
			public boolean onItemLongClick(AdapterView<?> arg0, View arg1,
                    int pos, long arg3) {
                System.out.println("hh longgggggggggggggggggggggggggggg click");
               
                registerForContextMenu(mListView);
                getActivity().openContextMenu(mListView);
//              if(lastLoded == UPLOADS){
//                  
//                  if(!videosVo.getInnerTopVideosVos().get(pos).isChecked())
//                      videosVo.getInnerTopVideosVos().get(pos).setChecked(true);
//                  else
//                      videosVo.getInnerTopVideosVos().get(pos).setChecked(false);
//                  
//                  adapterTopvideos.notifyDataSetChanged();
//              }
                return true;   
            }
        });
		
		
		
		//RadioGrupo.clearCheck();
		
		
		
		return view;
		 
	
		
	}
	
	
	public void  onCreateContextMenu(ContextMenu menu,View view,ContextMenuInfo menuInfo)
	{super.onCreateContextMenu(menu, view, menuInfo);
	
	
	   menu.setHeaderTitle("Acciones");
	   menu.add(0,view.getId(),0,"Vender");
	   menu.add(0,view.getId(),0,"Prueba");
	}
	
	
	public boolean onContextItemSelected(MenuItem item)
	{
		AdapterView.AdapterContextMenuInfo info =(AdapterView.AdapterContextMenuInfo)item.getMenuInfo();
	
		if (item.getTitle()=="Vender")
		{
			
			Toast.makeText(getActivity(), "Este es el primero", Toast.LENGTH_LONG).show();
			
			return true;
		}
		else
			return false;
		
	}
	
	
	public void onActivityCreated(Bundle savedInstanceState)
	{
		super.onActivityCreated(savedInstanceState);
		
		//new	LoadAllProducts().execute();
		
   //public void onRadioButtonClicked(View view)
		
		OnClickListener Listener=new OnClickListener()
		{
        public void onClick(View v) {
               RadioButton rb = (RadioButton) v;
               Toast.makeText(getActivity(), rb.getText(),    Toast.LENGTH_SHORT).show();
               if (rb.getText().equals("Por Tipo"))
               {
            	   
            	   
            	   DesplegadoTipo.setAdapter(null);
            	   
          objetoDetalle.SetNombre(NombreCliente.getEditableText().toString());
          Toast.makeText(getActivity(), "EL NOMBRE"+NombreCliente.getEditableText().toString(), Toast.LENGTH_LONG).show();
         
          objetoDetalle.SetNombre(NombreCliente.getEditableText().toString());
          //Intent i =new Intent(getActivity(),DetalleActivity.class);
         // i.putExtra("Nombre",NombreCliente.getEditableText().toString() );
         
          new LoadSucursales().execute();
            	
            	
              }
               else
               {
            		DesplegadoTipo.setAdapter(null);
            		
            	
             	
               }
            		   
            		
        }

		private String ValueOf(Editable text) {
			// TODO Auto-generated method stub
			return null;
		}
  };
		RadioRaza.setOnClickListener(Listener);
		RadioTipoGanado.setOnClickListener(Listener);
		
			
		
		
		RefreshList();
		Log.d("1"," msg");
	}

	  class LoadAllProducts extends AsyncTask<String, String, Bundle> {
			
	   		/**
	   		 * Before starting background thread Show Progress Dialog
	   		 * */
	   		@Override
	   		protected void onPreExecute() {
	   			super.onPreExecute();
	   			pDialog = new ProgressDialog(getActivity());
	   			pDialog.setMessage("Cargando Ganados. Espere un momento...");
	   			pDialog.setIndeterminate(false);
	   			pDialog.setCancelable(false);
	   			pDialog.show();
	   		}
	
	   		/**
	   		 * getting All sucursales from url
	   		 * */
	   		
	       
	       
	       
	       
	   		protected Bundle doInBackground(String... args) {
	   			// Building Parameters
	   			Bundle data = new Bundle();
	   			List<NameValuePair> params = new ArrayList<NameValuePair>();
	   			params.add(new BasicNameValuePair("codbarra","999"));//codbarratxt.getText().toString().trim()));
	   			// getting JSON string from URL
	   			   String url_all_products = "http://192.168.16.2/android_connectmio/TraemiArticulos.php";
	   			JSONObject json = jParser.makeHttpRequest(url_all_products, "GET", params);
	   			
	   			// Check your log cat for JSON reponse
	   			//if(json == null) return null;
	   			
	   			Log.d("All Products: ", json.toString());
	
	   			try {
	   				// Checking for SUCCESS TAG
	   				 success = json.getInt(TAG_SUCCESS);
	   				Log.d("success: ", String.valueOf(json.getInt(TAG_SUCCESS)));
	   				if (success == 1) {
	   					// sucursales found
	   					// Getting Array of Products
	   				Item = json.getJSONArray(TAG_PRODUCTOS);
	   					JSONObject c = Item.getJSONObject(0);
	   					
	   					
	   					String id = c.getString(TAG_PID);
						String unidad=c.getString("cantidad");
						String name = c.getString(TAG_NAME)   								;
						String precio=c.getString("precio");
						// creating new HashMap
						
						
						data.putString(TAG_PID, id);
						data.putString("cantidad", unidad);
						data.putString(TAG_NAME, name);
						data.putString("precio", precio);
						//data.putString("prueba", valor);
											
					

					
							
						
					
	   				} 
	   				else {
	   					// no sucursales found
	   					// Launch Add New product Activity
	   				/*	Intent i = new Intent(getApplicationContext(),
	   							CodbarActivity.class);
	   					// Closing all previous activities
	   					i.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
	   					startActivity(i);*/
	   					/*runOnUiThread(new Runnable() 
						{
						   public void run() 
						   {
							   Toast.makeText(getActivity(),"No se Encuentra Producto", Toast.LENGTH_LONG).show();
						   }
						}); */
	   					
	   				}
	   			} catch (JSONException e) {
	   				e.printStackTrace();
	   			}
	   			return data;
	   		}
	
	   		/**
	   		 * After completing background task Dismiss the progress dialog
	   		 * **/
	   		protected void onPostExecute(Bundle data) {
	   			// dismiss the dialog after getting all sucursales
	   			pDialog.dismiss();
	   			
	   	
	   			if(success==1)
					{
			   				HashMap<String, String> map = new HashMap<String, String>();
							
			   			map.put(TAG_PID, data.getString(TAG_PID));
						map.put("cantidad", data.getString("cantidad"));
						map.put(TAG_NAME, data.getString(TAG_NAME));
						map.put(TAG_PRECIO, data.getString("precio"));
						//map.put("prueba", data.getString("prueba"));
	   			
						Log.d("log", "Valor de Succes"+success);		
						
				ListItem.add(map);
				
				
			
				
				
				
	   			Log.d("P", "LLENANDO ARREGLO"+ListItem.toString());
	   			//RefreshList();
	   			
	   			
	   			
	   			
	   			
	   			
	   			/*
	   			cantidaddatos=new ArrayList();
	   			
	   			for(int a=0;a<productsList.size();a++)
	   			{
	   				cantidaddatos.add(ListItem.get(a).get("cantidad"));
	   			}
	   			
	   			
	   			Log.d("Pa", "LLENANDO ARREGLO cantidad datos"+cantidaddatos.toString());
	   			
	   			cantidadPrueba=productsList.get(0).get("cantidad");
	   			*/
	   			
					}
	   			else
	   			{
	   			// updating UI from Background Thread
	   			/*runOnUiThread(new Runnable() {
	   				public void run() {
	   					/**
	   					 * 
	   					 * 
	   					 * Updating parsed JSON data into ListView
	   					 * 
	   					
	   					int success;
						if(success==1)
	   					{
	   					Log.d("estes es mi lista", ListItem.toString());
	   					
	   				
	   					
	   				
	   				
	   					}
	   					else
	   					{ 
	   						
	   				Toast.makeText(FragmentTab1.this,"No se Encuentra Producto", Toast.LENGTH_LONG).show();
	   						
		   					
	   					}
	   				}
	
	   				
	   			});*/
	
	   		}
	   		}
	   	}
	  
	 

	  
	  class LoadSucursales extends AsyncTask<String, String, Bundle> {
			
	   		/**
	   		 * Before starting background thread Show Progress Dialog
	   		 * */
	   		@Override
	   		protected void onPreExecute() {
	   			super.onPreExecute();
	   			/*pDialog = new ProgressDialog(getActivity());
	   			pDialog.setMessage("Cargando Ganados. Espere un momento...");
	   			pDialog.setIndeterminate(false);
	   			pDialog.setCancelable(false);
	   			pDialog.show();*/
	   		}
	
	   		/**
	   		 * getting All sucursales from url
	   		 * */
	   		
	       
	       
	       
	       
	   		protected Bundle doInBackground(String... args) {
	   			// Building Parameters
	   			Bundle data = new Bundle();
	   			List<NameValuePair> params = new ArrayList<NameValuePair>();
	   			
	   			// getting JSON string from URL
	   			
	   			
	   				url_all_Sucursales = "http://10.0.0.2/android_connectmio/php_recuperaTipoGanado.php";
	   			
	   			   JSONObject json = jParser.makeHttpRequest(url_all_Sucursales, "GET", params);
	   			
	   			// Check your log cat for JSON reponse
	   			//if(json == null) return null;
	   			
	   			Log.d("All : ", json.toString());
	
	   			try {
	   				// Checking for SUCCESS TAG
	   				 success = json.getInt(TAG_SUCCESS);
	   				Log.d("success: ", String.valueOf(json.getInt(TAG_SUCCESS)));
	   				if (success == 1) {
	   					// sucursales found
	   					// Getting Array of Products
	   				Item = json.getJSONArray(TAG_TIPOGANADO);
	   					
	   				for(int i=0;i<Item.length();i++)
	   				{
	   				JSONObject c = Item.getJSONObject(i);
	   					
	   					
	   					String idsucursal= c.getString("idtipos_ganados");
						String Nombre=c.getString("tipo");
						
						// creating new HashMap
						
						HashMap<String,String>map=new HashMap<String,String>();
	   				
	   				map.put("idtipos_ganados", idsucursal);
	   				map.put( "tipo",Nombre);
						
	   				Ganados.add(map);
						
	   				}	
						
											
					

	   					
							
						
					
	   				} 
	   				else {
	   					//no Sucursales
	   					
	   				}
	   			} catch (JSONException e) {
	   				e.printStackTrace();
	   			}
	   			return null;
	   		}
	
	   		/**
	   		 * After completing background task Dismiss the progress dialog
	   		 * **/
	   		protected void onPostExecute(Bundle data) {
	   			// dismiss the dialog after getting all sucursales
	   		//	pDialog.dismiss();
	   			
	   		
	   			
	   			if(success==1)
					{
			   			
			
	   				
	   				
	   				sa = new ArrayList();
	   				
				     sa.clear();
					//String [] countries = productsList.toArray(new String[Sucursales.size()]);
					for(int a=0;a<Ganados.size();a++)	
					{
						//Toast.makeText(getApplicationContext(), Sucursales.get(a).get("codbarra").toString(), Toast.LENGTH_LONG).show();
					sa.add(Ganados.get(a).get("tipo").toString());
						
						
					
						//B[a]=Data.getString("nombre");
					}
		   			
	   				
	   				
	   				
	   				
	   				
	   				
	   				
				
			        ArrayAdapter<String> adaptador=new ArrayAdapter<String>(
					getActivity(),android.R.layout.simple_spinner_item,sa);
				
				adaptador.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
				adaptador.setNotifyOnChange(false);
			
				DesplegadoTipo.setAdapter(adaptador);
				
	   			Log.d("P", "LLENANDO ARREGLO"+ListItem.toString());
	   			//RefreshList();
	   			
	   			
	   			
	   			
	   			
	   			
	   			/*
	   			cantidaddatos=new ArrayList();
	   			
	   			for(int a=0;a<productsList.size();a++)
	   			{
	   				cantidaddatos.add(ListItem.get(a).get("cantidad"));
	   			}
	   			
	   			
	   			Log.d("Pa", "LLENANDO ARREGLO cantidad datos"+cantidaddatos.toString());
	   			
	   			cantidadPrueba=productsList.get(0).get("cantidad");
	   			*/
	   			
					}
	   			else
	   			{
	   			// updating UI from Background Thread
	   			/*runOnUiThread(new Runnable() {
	   				public void run() {
	   					/**
	   					 * 
	   					 * 
	   					 * Updating parsed JSON data into ListView
	   					 * 
	   					
	   					int success;
						if(success==1)
	   					{
	   					Log.d("estes es mi lista", ListItem.toString());
	   					
	   				
	   					
	   				
	   				
	   					}
	   					else
	   					{ 
	   						
	   				Toast.makeText(FragmentTab1.this,"No se Encuentra Producto", Toast.LENGTH_LONG).show();
	   						
		   					
	   					}
	   				}
	
	   				
	   			});*/
	
	   		}
	   		}
	   	}
	  
	  
	  
	  
	  
	  
	  
	  
	  
	  
	  
	  
	  
	  
	  
	  
	  
	  
	  
	  
	  
	  public void RefreshList()
      {
   	   mAdapter = new SimpleAdapter(
					getActivity(), ListItem,
					R.layout.list_item, new String[] { TAG_PID,
							TAG_NAME,TAG_PRECIO,"cantidad"},
					new int[] { R.id.pid, R.id.name,R.id.Precio,R.id.Cantidad });

		//	((BaseAdapter) mAdapter).notifyDataSetChanged();
				mListView.setAdapter(mAdapter);
      }

	  
	public void onSaveInstanceState(Bundle outState) {
		super.onSaveInstanceState(outState);
		setUserVisibleHint(true);
		
		
	      //ListItem = new ArrayList<HashMap<String, String>>();
	      
	      
		  registerForContextMenu(mListView);
		
	}

	
	
	
	
	
	
}
